/*
 * @Autor: xgq
 * @Description: 
 * @Version: 1.0
 * @Date: 2020-05-11 14:18:40
 */
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const log4js = require('../config/log4js').log4js
const logger = log4js.getLogger('m_banner');

module.exports = (sequelize, DataTypes ) => {

  class m_Banner extends Sequelize.Model {

    static getBannerList(where = {}){
      let list = this.findAll({ where: where, order:[ ['sort','ASC'] ] })
      return list;
    }

    //删除banner
    static async deleteBanner(params) {
      this.sequelize.transaction(t => {
          // 在事务中执行操作
          return this.destroy({ where: { id: params.id } },{transaction : t})
              .then(() => {
                  return this.decrement(['sort'], { where: { sort: { $gt: params.sort } }},{transaction : t} )
              });
      }).then(() => {
          return true
      }).catch(() => {
          return false
      });
    }

    //检查标题
    static async checkTitle(params) {
      var querydata = []
      let sql = `select * from banner where title=?`
      querydata = await sequelize.query(sql,{replacements: [params],type: sequelize.QueryTypes.SELECT})
      return querydata
    }

    //查询banner列表
    static async listBanner(params) {
      var querydata = [];
      var [page = 1, pagesize = 20, limit = 0] = [params.page, params.pagesize, params.limit]
      var where = {}
      let condition = {
          attributes: ['title', 'sort', 'status', 'position', 'link', 'link_id', 'link_name', 'link_type', 'create_time', 'id', 'thumbnail'],
          offset: pagesize * (page - 1),
          raw: true,
          limit: parseInt(pagesize)
      }
      if (params.id != null && params.id != '') {
        where.id = { "$like": '%' + params.id + '%' }
      }
      if (params.title != undefined && params.title != '') {
          where.title = { "$like": '%' + params.title + '%' }
      }
      if (params.sort != null && params.sort != '') {
          where.sort = params.sort
      }
      if (params.status != null && params.status !== '') {
          where.status = params.status
      }

      if (params.position != null && params.position != '') {
          where.position = { [Op.in]: params.position }
      }
      condition.where = where
      condition.order = [['sort', 'ASC']]
      querydata = await this.findAndCountAll(condition);
      return querydata
    }

     //新增
    static async addBanner(params) {
      let counts=0
      let sql=`select count(1) as count from banner`
      counts = await sequelize.query(sql,{type: sequelize.QueryTypes.SELECT})
      let result
      let createTime = parseInt(new Date().getTime() / 1000)
      result = await this.create({
          title: params.title, sort: counts[0].count+1, status: '0', position: '1',
          link: params.link, create_time: createTime, thumbnail: params.thumbnail
      });
      return result

    }

    //新增底部banner
    static async addFootBanner(params) {
      let counts=0
      let sql=`select count(1) as count from banner`
      counts = await sequelize.query(sql,{type: sequelize.QueryTypes.SELECT})
      let result
      let createTime = parseInt(new Date().getTime() / 1000)
      let obj = {
        title: params.title, sort: counts[0].count+1, status: 0, position: 2,
        link: params.link, link_type: params.link_type, 
        create_time: createTime, 
        thumbnail: params.thumbnail
      }
      if( params.link_type !== 4 ){
        obj.link_id = params.link_id
        obj.link_name = params.link_name
      }

      result = await this.create(obj);
      return result
    }

     //更新顶部banner
    static async updateBanner(params) {
      var queryData
      queryData=await this.update({'title':params.title,'thumbnail':params.thumbnail},{where:{id:params.id}})
      return queryData
    }

    //更新底部banner
    static async updateFootBanner(params) {
      return await this.update({
        title:params.title,
        link:params.link,
        link_type:params.link_type,
        link_id: params.link_id == '' ? null : params.link_id,
        link_name: params.link_name,
        thumbnail:params.thumbnail
        },{where:{id:params.id}}).then(re => {
        return true
      }).catch(err => {
        logger.error(err)
        return false
      })

    }

    //关闭
    static async bannerOff(params) {
      let queryData=await this.update({status:1},{where:{id:params}})
      return queryData
    }
    //开启
    static async bannerUp(params) {
      let queryData=await this.update({status:0},{where:{id:params}})
      return queryData
    }
    static async bannerSort(params) {
      var queryData = []
      var valueArr = []
      let sql = `select id,sort from banner order by sort asc`
      queryData = await sequelize.query(sql,{type: sequelize.QueryTypes.SELECT})
      //start拖动的目的地
      //end从哪一行开始拖动的
      //start《end从后往前拖动   start》end从前往后拖动
      var value={}
      if (parseInt(params.start) < parseInt(params.end)) {//从后往前拖动
          for (var i = parseInt(params.start); i <= parseInt(params.end); i++) {
              if (i == parseInt(params.end)) {
                   value = {
                      id: queryData[i].id,
                      sort: parseInt(params.start) + 1
                  };
              } else {
                   value = {
                      id: queryData[i].id,
                      sort: queryData[i].sort + 1,
                  };
              }
              valueArr.push(value)
          }
      } else if (parseInt(params.start) > parseInt(params.end)) {//从前往后拖动
          for (let i = parseInt(params.end); i <= parseInt(params.start); i++) {
              if (i == parseInt(params.end)) {
                   value = {
                      id: queryData[i].id,
                      sort: parseInt(params.start) + 1
                  }
              } else {
                   value = {
                      id: queryData[i].id,
                      sort: queryData[i].sort - 1,
                  };
              }

              valueArr.push(value)
          }
      }
      var updateData = []
      updateData = await this.bulkCreate(valueArr, { updateOnDuplicate: ["sort"] });
      return updateData
    }

    static async getBannerByid(id){
      let banner=await this.findOne({where:{id},raw:true})
      return banner;
    }

  }
  
  m_Banner.init({
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    title: { type: DataTypes.STRING(200) },
    sort: { type: DataTypes.INTEGER },
    status: { type: DataTypes.INTEGER, defaultValue:0 },
    position: { type: DataTypes.INTEGER(6) },
    link: { type: DataTypes.STRING(255) },
    link_id: { type: DataTypes.INTEGER },
    link_name: { type: DataTypes.STRING(45) },
    link_type: { type: DataTypes.STRING(255) },
    create_time: { type: DataTypes.INTEGER },
    thumbnail: { type: DataTypes.STRING(255) }
  }, {
    sequelize,
    modelName: 'banner',
    freezeTableName: true,
    timestamps: false
  });

  return m_Banner;
}